﻿using M_Purchase.Api.Appliction.Command.PurchCommand;
using M_Purchase.Domain;
using M_Purchase.Domain.DTO;
using M_Purchase.Repository.PurchaseInterface;
using MediatR;

namespace M_Purchase.Api.Appliction.CommandHandlers.PurchCommandHandler
{
    /// <summary>
    /// 显示采购
    /// </summary>
    public class PurchListCommandHandler : IRequestHandler<PurchListCommand, PageDTO<Purch>>
    {
        private readonly IPurchRepository _purchRepository;
        public PurchListCommandHandler(IPurchRepository purchRepository)
        {
            _purchRepository = purchRepository;
        }
        public async Task<PageDTO<Purch>> Handle(PurchListCommand request, CancellationToken cancellationToken)
        {
            var PurList = await _purchRepository.GetAsync(d=>!d.IsDeleted);
            if (!string.IsNullOrEmpty(request.PurchaseCode))
            {
                PurList= PurList.Where(d=>d.PurchaseCode.Contains(request.PurchaseCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.PurchaseDate))
            {
                PurList=PurList.Where(d=>d.PurchaseDate==Convert.ToDateTime(request.PurchaseDate)).ToList();
            }
            if (!string.IsNullOrEmpty(request.PurchaseSart))
            {
                PurList=PurList.Where(d=>d.PurchaseSart==request.PurchaseSart).ToList();
            }
            if (request.PageSize == null)
            {
                request.PageSize = PurList.Count();
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            PageDTO<Purch> page = new PageDTO<Purch>();
            page.TotalCount= PurList.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)request.PageSize);
            page.list= PurList.OrderByDescending(d=>d.CreatedBy).Skip((int)(request.PageIndex-1)*(int)request.PageSize).Take((int)request.PageSize).ToList();
            return page;

        }
    }
}
